<template>
    <div class="iframe-container" v-show="show" ref="container"></div>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import TemplateRaw from './template.html?raw';
import { CodeEditor } from './Store'

const show = ref(true);
const container = ref();
let sandbox: HTMLIFrameElement

function RunderSandbox() {

    if (sandbox) {
        // clear prev sandbox
        container.value.removeChild(sandbox)
    }

    sandbox = document.createElement('iframe')
    sandbox.setAttribute(
        'sandbox',
        [
            'allow-forms',
            'allow-modals',
            'allow-pointer-lock',
            'allow-popups',
            'allow-same-origin',
            'allow-scripts',
            'allow-top-navigation-by-user-activation'
        ].join(' ')
    );
    var CodeStr = [];
    for (const key in CodeEditor.state) {
        const element = CodeEditor.state[key];
        CodeStr.push(`'/${key}':\`${element.code}\``);
    };
    const TemplateStr = TemplateRaw.replace(/<!--CODE_MAP-->/, CodeStr.join(','));
    sandbox.srcdoc = TemplateStr;
    container.value.appendChild(sandbox);
}


CodeEditor.onPageRunder(RunderSandbox);


</script>
<style lang="less" scoped>
.iframe-container,
.iframe-container :deep(iframe) {
    width: 100%;
    height: 100%;
    border: none;
    background-color: #fff;
}
</style>